package com.taotao.order.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbOrderItemMapper;
import com.taotao.mapper.TbOrderMapper;
import com.taotao.mapper.TbOrderShippingMapper;
import com.taotao.order.component.JedisClient;
import com.taotao.order.pojo.OrderInfo;
import com.taotao.pojo.TbOrderItem;
import com.taotao.pojo.TbOrderShipping;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private TbOrderMapper orderMapper;
	@Autowired
	private TbOrderItemMapper orderItemMapper;
	@Autowired
	private TbOrderShippingMapper orderShippingMapper;

	@Autowired
	private JedisClient jedisClient;

	@Value("${REDIS_ORDER_GEN_KEY}")
	private String REDIS_ORDER_GEN;
	@Value("${ORDER_BEGIN_ID}")
	private String ORDER_BEGIN_ID;
	@Value("${REDIS_ORDER_ITEM_GEN_KEY}")
	private String REDIS_ORDER_ITEM_GEN;

	/**
	 * 创建保存新生成用户订单
	 */
	@Override
	public TaotaoResult createOrder(OrderInfo orderInfo) {
		// 1.生成redis订单号
		String id = jedisClient.get(REDIS_ORDER_GEN);
		if (StringUtils.isBlank(id)) {
			jedisClient.set(REDIS_ORDER_GEN, ORDER_BEGIN_ID);
		}
		// 2.补全orderInfo信息
		Long orderId = jedisClient.incr(REDIS_ORDER_GEN);
		orderInfo.setOrderId(orderId.toString());
		orderInfo.setStatus(1);
		Date date = new Date();
		orderInfo.setCreateTime(date);
		orderInfo.setUpdateTime(date);
		// 3.插入订单表到数据库
		orderMapper.insertSelective(orderInfo);
		// 4.插入订单商品明细到数据库
		List<TbOrderItem> orderItems = orderInfo.getOrderItems();
		for (TbOrderItem tbOrderItem : orderItems) {
			Long orderItemId = jedisClient.incr(REDIS_ORDER_ITEM_GEN);
			tbOrderItem.setId(orderItemId.toString());
			tbOrderItem.setOrderId(orderId.toString());
			orderItemMapper.insertSelective(tbOrderItem);
		}
		// 5.插入订单物流明细到数据库
		TbOrderShipping orderShipping = orderInfo.getOrderShipping();
		orderShipping.setOrderId(orderId.toString());
		orderShipping.setCreated(date);
		orderShipping.setUpdated(date);
		orderShippingMapper.insertSelective(orderShipping);
		// 返回订单号
		return TaotaoResult.ok(orderId);
	}

}
